package com.cakeclient.clientsoap.contract;


import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;

import java.lang.reflect.Field;
import java.util.Hashtable;

public abstract class ContractObject implements KvmSerializable {
    public ContractObject() {
    }

    public abstract void fill(SoapObject soapObject);

    public Object getProperty(int intPropertyIndex) {
        Object val = null;
        try {
            val = this.getClass().getFields()[intPropertyIndex].get(this);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if (val != null) {
            return val;
        } else {
            return null;
        }
    }

    public int getPropertyCount() {
        return this.getClass().getFields().length;
    }

    public void getPropertyInfo(int intPropertyIndex, Hashtable arg1, PropertyInfo info) {
        Field field = this.getClass().getFields()[intPropertyIndex];
        info.name = field.getName();
        info.type = field.getType();
    }

    public void setProperty(int intPropertyIndex, Object objectPropertyNewValue) {
        Field field = this.getClass().getFields()[intPropertyIndex];
        try {
            field.set(this, objectPropertyNewValue);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public PropertyInfo toPropertyInfo() {
        PropertyInfo value = new PropertyInfo();
        value.setName(this.getClass().getName());
        value.setType(this.getClass());
        value.setValue(this);
        return value;
    }

    public PropertyInfo toPropertyInfo(String name) {
        PropertyInfo value = new PropertyInfo();
        value.setName(name);
        value.setType(this.getClass());
        value.setValue(this);
        return value;
    }


    public SoapObject toSoapObject(String namespace, String name) {
        SoapObject result = new SoapObject(namespace, name);
        for (Field v : this.getClass().getFields()) {
            try {
                Object o = v.get(this);
                if (o != null) {
                    if (o instanceof ContractObject) {
                        result.addSoapObject(((ContractObject) o).toSoapObject(namespace, v.getName()));
                    } else if (o instanceof SoapArray) {
                        result.addSoapObject(((SoapArray) o).toSoapObject(namespace, v.getName()));
                    } else {
                        result.addProperty(v.getName(), o.toString());
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}